import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useGameStore = defineStore('game', () => {
  // 游戏状态
  const gameStatus = ref('waiting') // waiting, playing, finished
  const gameTime = ref(0)
  const totalGameTime = ref(180)
  const isGameActive = ref(false)
  
  // 房间信息
  const currentRoom = ref(null)
  const roomCode = ref('')
  const roomName = ref('')
  const maxPlayers = ref(6)
  
  // 玩家信息
  const currentPlayer = ref(null)
  const players = ref([])
  const currentPlayerId = ref('')
  
  // 游戏数据
  const canvasData = ref(null)
  const paintActions = ref([])
  const playerScores = ref(new Map())
  
  // 连接状态
  const isConnected = ref(false)
  const connectionError = ref('')
  
  // 计算属性
  const currentPlayerIndex = computed(() => {
    return players.value.findIndex(p => p.id === currentPlayerId.value)
  })
  
  const isRoomOwner = computed(() => {
    return currentPlayer.value?.isOwner || false
  })
  
  const canStartGame = computed(() => {
    if (!isRoomOwner.value) return false
    const readyPlayers = players.value.filter(p => p.isReady)
    return readyPlayers.length >= 2 && readyPlayers.length === players.value.length
  })
  
  const sortedPlayers = computed(() => {
    return [...players.value].sort((a, b) => {
      const scoreA = playerScores.value.get(a.id) || 0
      const scoreB = playerScores.value.get(b.id) || 0
      return scoreB - scoreA
    })
  })
  
  const winner = computed(() => {
    if (gameStatus.value === 'finished' && sortedPlayers.value.length > 0) {
      return sortedPlayers.value[0]
    }
    return null
  })
  
  // 动作方法
  function setGameStatus(status) {
    gameStatus.value = status
    isGameActive.value = status === 'playing'
  }
  
  function setGameTime(time) {
    gameTime.value = time
  }
  
  function setTotalGameTime(time) {
    totalGameTime.value = time
  }
  
  function setCurrentRoom(room) {
    currentRoom.value = room
    if (room) {
      roomCode.value = room.roomCode
      roomName.value = room.name
      maxPlayers.value = room.maxPlayers
      totalGameTime.value = room.gameDuration
    }
  }
  
  function setCurrentPlayer(player) {
    currentPlayer.value = player
    currentPlayerId.value = player?.id || ''
  }
  
  function addPlayer(player) {
    const existingIndex = players.value.findIndex(p => p.id === player.id)
    if (existingIndex >= 0) {
      players.value[existingIndex] = { ...players.value[existingIndex], ...player }
    } else {
      players.value.push(player)
    }
  }
  
  function removePlayer(playerId) {
    const index = players.value.findIndex(p => p.id === playerId)
    if (index >= 0) {
      players.value.splice(index, 1)
    }
  }
  
  function updatePlayer(playerId, updates) {
    const player = players.value.find(p => p.id === playerId)
    if (player) {
      Object.assign(player, updates)
    }
  }
  
  function setPlayerReady(playerId, isReady) {
    updatePlayer(playerId, { isReady })
  }
  
  function setPlayerScore(playerId, score) {
    playerScores.value.set(playerId, score)
  }
  
  function addPaintAction(action) {
    paintActions.value.push(action)
    // 限制历史记录数量
    if (paintActions.value.length > 1000) {
      paintActions.value.shift()
    }
  }
  
  function clearPaintActions() {
    paintActions.value = []
  }
  
  function setCanvasData(data) {
    canvasData.value = data
  }
  
  function setConnectionStatus(connected, error = '') {
    isConnected.value = connected
    connectionError.value = error
  }
  
  function resetGame() {
    gameStatus.value = 'waiting'
    gameTime.value = 0
    isGameActive.value = false
    paintActions.value = []
    playerScores.value.clear()
    players.value.forEach(player => {
      player.isReady = false
      player.isPlaying = false
      player.areaCount = 0
    })
  }
  
  function resetRoom() {
    currentRoom.value = null
    roomCode.value = ''
    roomName.value = ''
    maxPlayers.value = 6
    currentPlayer.value = null
    currentPlayerId.value = ''
    players.value = []
    resetGame()
  }
  
  // 游戏逻辑方法
  function calculatePlayerArea() {
    // 这里应该实现面积计算逻辑
    // 暂时返回随机值用于演示
    return Math.floor(Math.random() * 1000) + 100
  }
  
  function startGame() {
    if (!canStartGame.value) return false
    
    setGameStatus('playing')
    gameTime.value = totalGameTime.value
    
    // 为所有玩家分配颜色
    const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD']
    players.value.forEach((player, index) => {
      player.color = colors[index % colors.length]
      player.isPlaying = true
      player.isReady = false
      player.areaCount = 0
    })
    
    return true
  }
  
  function endGame() {
    setGameStatus('finished')
    isGameActive.value = false
    
    // 计算最终得分
    players.value.forEach(player => {
      const area = calculatePlayerArea(player.id)
      player.areaCount = area
      setPlayerScore(player.id, area)
    })
  }
  
  function updateGameTime() {
    if (gameStatus.value === 'playing' && gameTime.value > 0) {
      gameTime.value--
      if (gameTime.value <= 0) {
        endGame()
      }
    }
  }
  
  return {
    // 状态
    gameStatus,
    gameTime,
    totalGameTime,
    isGameActive,
    currentRoom,
    roomCode,
    roomName,
    maxPlayers,
    currentPlayer,
    players,
    currentPlayerId,
    canvasData,
    paintActions,
    playerScores,
    isConnected,
    connectionError,
    
    // 计算属性
    currentPlayerIndex,
    isRoomOwner,
    canStartGame,
    sortedPlayers,
    winner,
    
    // 动作方法
    setGameStatus,
    setGameTime,
    setTotalGameTime,
    setCurrentRoom,
    setCurrentPlayer,
    addPlayer,
    removePlayer,
    updatePlayer,
    setPlayerReady,
    setPlayerScore,
    addPaintAction,
    clearPaintActions,
    setCanvasData,
    setConnectionStatus,
    resetGame,
    resetRoom,
    
    // 游戏逻辑方法
    calculatePlayerArea,
    startGame,
    endGame,
    updateGameTime
  }
}) 